package com.ruoyi.school.service.impl;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.school.Exception.BussnissExecption;
import com.ruoyi.school.config.MinioProperties;
import com.ruoyi.school.domain.*;
import com.ruoyi.school.mapper.*;
import com.ruoyi.school.service.MinioService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import com.ruoyi.school.domain.User;
import org.springframework.stereotype.Service;
import com.ruoyi.school.service.ILoveService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 主表模块Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-10
 */
@Service
public class LoveServiceImpl implements ILoveService {
    @Autowired
    private LoveMapper loveMapper;

    @Autowired
    private DianzanMapper dianzanMapper;

    @Autowired
    private CommonMapper commonMapper;

    @Autowired
    private PicUrlMapper picUrlMapper;

    @Autowired
    private GuanzhuMapper guanzhuMapper;
    @Autowired
     MinioClient minioClient;
    @Autowired
      MinioProperties minioProperties;


    /**
     * 查询主表模块
     *
     * @param id 主表模块主键
     * @return 主表模块
     */
    @Override
    public Love selectLoveById(Long id, Long loginId) {
        Love love = loveMapper.selectLoveById(id, loginId);
        PicUrl picUrl = new PicUrl();
        List<PicUrl> picUrls = picUrlMapper.selectPicUrlList(picUrl.setLoveId(love.getId()).setUserId(love.getUserId()));
        love.setPicUrls(picUrls);
        love.setViewCount(love.getViewCount() + 1);
        loveMapper.updateLove(love);
        return love;
    }

    @Override
    public List<Common> getCommon(Long id) {
        Common common = new Common().setLoveId(id);
        List<Common> commons = commonMapper.selectCommonList(common);
        if (!commons.isEmpty()) {
            commons = common(commons);
        }
        return commons;
    }

    @Override
    public boolean zan(Long loveId, User user) {
        Dianzan dianzan = new Dianzan().setLoveId(loveId).setUserId(user.getId());
        List<Dianzan> dianzans = dianzanMapper.selectDianzanList(dianzan);
        Love love = loveMapper.selectLoveById(loveId, null);
        if (dianzans.isEmpty()) {
            dianzan.setUserName(user.getUserName()).setUserPic(user.getUserPic());
            int i = dianzanMapper.insertDianzan(dianzan);
            love.setZanId(love.getZanId() + 1);
            loveMapper.updateLove(love);
        } else {
            Dianzan dianzan1 = dianzans.get(0);
            if (love.getZanId() >= 1) {
                love.setZanId(love.getZanId() - 1);
            }
            loveMapper.updateLove(love);
            dianzanMapper.deleteDianzanById(dianzan1.getId());
        }
        return false;
    }

    @Override
    public String guan(Guanzhu guanzhu) {
        if (guanzhu.getId() != guanzhu.getBuserId()) {
            Guanzhu guan = new Guanzhu();
            guan.setUserId(guanzhu.getUserId());
            guan.setBuserId(guanzhu.getBuserId());

            List<Guanzhu> guanzhuList = guanzhuMapper.selectGuanzhuList(guan);
            if (guanzhuList.isEmpty()) {
                guan.setUserName(guanzhu.getUserName());
                guan.setBuserName(guanzhu.getBuserName());
                System.err.println(guanzhu);
                guanzhuMapper.insertGuanzhu(guan);
            } else {
                Guanzhu guanzhu1 = guanzhuList.get(0);
                guanzhuMapper.deleteGuanzhuById(guanzhu1.getId());
            }
        } else {
            throw new BussnissExecption("自己不嫩关注自己");
        }

        return null;
    }

    @Override
    public List<Love> getLikeOrPush(Long index, Long userId, Long pushAble, String content) {
        List<Love> loveLis = new ArrayList<>();
        if (index == 2) {
            loveLis = loveMapper.getLike(index, userId);
        } else {
            loveLis = loveMapper.getPush(userId, pushAble, content);
        }
        if (loveLis.size() > 0 && !loveLis.isEmpty()) {
            PicUrl picUrl = new PicUrl();
            for (Love l : loveLis) {
                List<PicUrl> picUrls = picUrlMapper.selectPicUrlList(picUrl.setLoveId(l.getId()).setUserId(l.getUserId()));
                l.setPicUrls(picUrls);
            }
        }
        return loveLis;
    }

    @Override
    public List<TwoHeadType> gettype() {
        return loveMapper.getType();
    }

    @Override
    public int addCommon(Common common) {
        common.setCreateTime(new Date());
        Love love = loveMapper.selectLoveById(common.getLoveId(), null);
        loveMapper.updateLove(love.setPingId(love.getPingId() + 1));
        return commonMapper.insertCommon(common);
    }

    @Override
    public List<Love> getLoveByPersion(Long userId, Long myId) {
        List<Love> loves = loveMapper.getLoveByPersion(userId, myId);
        if (loves.size() > 0 && !loves.isEmpty()) {
            PicUrl picUrl = new PicUrl();
            for (Love l : loves) {
                List<PicUrl> picUrls = picUrlMapper.selectPicUrlList(picUrl.setLoveId(l.getId()).setUserId(l.getUserId()));
                l.setPicUrls(picUrls);

            }
        }
        return loves;
    }

    @Override
    @Transactional()
    public String loveAdd(Love love) {
        if (love.getCreateTime() == null) {
            love.setCreateTime(new Date());
        }
        love.setViewCount(0l);
        loveMapper.insertLove(love);
        PicUrl picUrl = new PicUrl();
        List<String> picUrls = love.getUrls();
        picUrl.setUserName(love.getUserName());
        picUrl.setUserId(love.getUserId());
        picUrl.setLoveId(love.getId());
        picUrl.setType(love.getType());
        if (!picUrls.isEmpty() && picUrls.size() > 0) {
            for (String url : picUrls) {
                picUrl.setPicUrl(url);
                picUrlMapper.insertPicUrl(picUrl);
            }
        }

        return null;
    }

    @Override
    public String removeDian(Long userId, Long dianId) {
        if (StringUtils.isEmpty(String.valueOf(userId)) || StringUtils.isEmpty(String.valueOf(dianId))) {
            throw new BussnissExecption("请登录");
        }
        Dianzan dianzan = new Dianzan().setUserId(userId).setLoveId(dianId);
        dianzanMapper.deleteDianzanById(dianzan.getId());
        return null;
    }

    @Override
    @Transactional
    public String removeLovePush(Long loveId) {
        if (StringUtils.isEmpty(String.valueOf(loveId))) {
            throw new BussnissExecption("请选择要删除的内容");
        }
        loveMapper.deleteDianByloveId(loveId);
        loveMapper.deletePicByloveId(loveId);
        loveMapper.deleteLoveById(loveId);

        return null;
    }

    @Override
    public void pressImag() throws IOException {
//        List<PicUrl> picUrlList=picUrlMapper.selectBytoday();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
//        for (PicUrl l : picUrlList) {
        URL url = new URL("http://39.98.162.10:9000/school/95d0070412a74df1b5ebe244600b999e.jpg");
            Thumbnails.of(url)
                    .scale(1D)
                    .toOutputStream(output);
        InputStream inputStream = streamTran(output);
        try {
            uploadInputStream("test2.jpg",inputStream,"image/JPG");
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (InsufficientDataException e) {
            e.printStackTrace();
        } catch (ErrorResponseException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidResponseException e) {
            e.printStackTrace();
        } catch (XmlParserException e) {
            e.printStackTrace();
        } catch (InternalException e) {
            e.printStackTrace();
        }

//        }
    }
    private InputStream streamTran(ByteArrayOutputStream in) {
        return new ByteArrayInputStream(in.toByteArray());
    }
    private void uploadInputStream(String filename,InputStream inputStream,String fileType) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        minioClient.putObject(
                PutObjectArgs.builder().bucket("school").object(filename).stream(
                                inputStream, -1, minioProperties.getFileSize())
                        .contentType(fileType)
                        .build());
    }
    /**
     * 查询主表模块列表
     *
     * @param love 主表模块
     * @return 主表模块
     */
    @Override
    public List<Love> selectLoveList(Love love) {
        System.err.println(love);
        List<Love> loves = loveMapper.selectLoveList(love);
        if (loves.size() > 0 && !loves.isEmpty()) {
//            Common common = new Common();
            PicUrl picUrl = new PicUrl();
//            Dianzan dianzan = new Dianzan();
//            Guanzhu guanzhu = new Guanzhu();
            for (Love l : loves) {
//                List<Dianzan> dianzans = dianzanMapper.selectDianzanList(dianzan.setLoveId(l.getId()).setUserId(l.getUserId()));
//                l.setDianzanList(dianzans);

//                List<Common> commons = commonMapper.selectCommonList(common.setLoveId(l.getId()).setUserId(l.getUserId()));
//                l.setCommonList(common(commons));

                List<PicUrl> picUrls = picUrlMapper.selectPicUrlList(picUrl.setLoveId(l.getId()).setUserId(l.getUserId()));
                l.setPicUrls(picUrls);

//                if (!StringUtils.isEmpty(String.valueOf(l.getLoginId()))){
//                    List<Guanzhu> guanzhus = guanzhuMapper.selectGuanzhuList(guanzhu.setUserId(love.getLoginId()).setBuserId(l.getUserId()));
//                    if (!guanzhus.isEmpty()){
//                        l.setIsguan(1l);
//                    }else {
//                        l.setIsguan(0l);
//                    }
//                }else {
//                    l.setIsguan(0l);
//                }

            }
        }
        return loves;
    }

    public List<Common> common(List<Common> dianzanList) {
        List<Common> parenList = null;
        if (!dianzanList.isEmpty()) {
            parenList = dianzanList.stream().filter(item -> item.getParentId() == null).collect(Collectors.toList());
            for (Common parent : parenList) {
                List<Common> chren = commonMapper.getListByParentId(parent.getId());
                parent.setCommonList(chren);
            }
        }
        return parenList;
    }

    /**
     * 新增主表模块
     *
     * @param love 主表模块
     * @return 结果
     */
    @Override
    public int insertLove(Love love) {
        love.setCreateTime(DateUtils.getNowDate());
        return loveMapper.insertLove(love);
    }

    /**
     * 修改主表模块
     *
     * @param love 主表模块
     * @return 结果
     */
    @Override
    public int updateLove(Love love) {
        return loveMapper.updateLove(love);
    }


    @Override
    public int deleteLoveById(Long id) {
        return loveMapper.deleteLoveById(id);
    }


}
